package com.apex.sdk.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSON;
import com.apex.bluetooth.callback.OtaCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.model.EABleOta;
import com.apex.bluetooth.model.TitanOtaFileInfo;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivityTitanOtaBinding;
import com.apex.sdk.dialog.WaitingDialog;
import com.smartcomm.lz4.PreLz4;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


public class TitanOtaActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();

    private WaitingDialog waitingDialog;


    private String agpsFilePath;
    private String dialFilePath;
    int dialId = 10;
    private int oriFileSize;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x40) {
                if (TextUtils.isEmpty(agpsFilePath) || !new File(agpsFilePath).exists()) {
                    Log.e(TAG, "agps文件不存在");
                    if (waitingDialog != null) {
                        if (waitingDialog.isShowing()) {
                            waitingDialog.dismiss();
                        }
                    }
                } else {
                    EABleOta eaBleOta = new EABleOta();
                    eaBleOta.setFilePath(agpsFilePath);
                    eaBleOta.setOtaType(EABleOta.OtaType.agps);
                    List<EABleOta> otaList = new ArrayList<>();
                    otaList.add(eaBleOta);
                    EABleManager.getInstance().otaUpdate(otaList, new OtaCallback() {
                        @Override
                        public void success() {
                            Log.e(TAG, "OTA成功");
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x42);
                            }

                        }

                        @Override
                        public void progress(int progress) {
                            Log.e(TAG, "OTA进度:" + progress);

                        }

                        @Override
                        public void mutualFail(int errorCode) {
                            Log.e(TAG, "OTA失败");
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x42);
                            }
                        }
                    });

                }
            } else if (msg.what == 0x42) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
            } else if (msg.what == 0x43) {
                if (TextUtils.isEmpty(dialFilePath) || !new File(dialFilePath).exists()) {
                    Log.e(TAG, "表盘文件不存在");
                    if (waitingDialog != null) {
                        if (waitingDialog.isShowing()) {
                            waitingDialog.dismiss();
                        }
                    }
                } else {
                    EABleOta eaBleOta = new EABleOta();
                    eaBleOta.setFilePath(dialFilePath);
                    eaBleOta.setOtaType(EABleOta.OtaType.user_wf);
                    eaBleOta.setVersionCode(++dialId);
                    eaBleOta.setCustomDialStyle(oriFileSize);
                    List<EABleOta> otaList = new ArrayList<>();
                    otaList.add(eaBleOta);

                    EABleManager.getInstance().otaUpdate(otaList, new OtaCallback() {
                        @Override
                        public void success() {
                            Log.e(TAG, "OTA成功");
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x42);
                            }

                        }

                        @Override
                        public void progress(int progress) {
                            Log.e(TAG, "OTA进度:" + progress);

                        }

                        @Override
                        public void mutualFail(int errorCode) {
                            Log.e(TAG, "OTA失败");
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x42);
                            }
                        }
                    });

                }
            } else if (msg.what == 0x44) {
                EABleOta eaBleOta = (EABleOta) msg.obj;
                if (eaBleOta == null) {
                    Log.e(TAG, "固件文件处理出现问题");
                    if (waitingDialog != null) {
                        if (waitingDialog.isShowing()) {
                            waitingDialog.dismiss();
                        }
                    }
                } else {
                    List<EABleOta> otaList = new ArrayList<>();
                    otaList.add(eaBleOta);
                    EABleManager.getInstance().otaUpdate(otaList, new OtaCallback() {
                        @Override
                        public void success() {
                            Log.e(TAG, "OTA成功");
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x42);
                            }

                        }

                        @Override
                        public void progress(int progress) {
                            Log.e(TAG, "OTA进度:" + progress);

                        }

                        @Override
                        public void mutualFail(int errorCode) {
                            Log.e(TAG, "OTA失败");
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x42);
                            }
                        }
                    });

                }
            }
        }
    };

    ActivityTitanOtaBinding activityTitanOtaBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityTitanOtaBinding = ActivityTitanOtaBinding.inflate(getLayoutInflater());
        setContentView(activityTitanOtaBinding.getRoot());
        activityTitanOtaBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityTitanOtaBinding.tool);
        getSupportActionBar().setTitle(null);
        activityTitanOtaBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        activityTitanOtaBinding.agpsUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(TitanOtaActivity.this);
                }
                if (waitingDialog.isShowing()) {
                    return;
                }
                waitingDialog.show();
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        getAgpsFilePath();
                        if (mHandler != null) {
                            mHandler.sendEmptyMessage(0x40);
                        }

                    }
                }.start();


            }
        });
        activityTitanOtaBinding.dialUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(TitanOtaActivity.this);
                }
                if (waitingDialog.isShowing()) {
                    return;
                }
                waitingDialog.show();
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        getDialFilePath();
                        if (mHandler != null) {
                            mHandler.sendEmptyMessage(0x43);
                        }

                    }
                }.start();
            }
        });
        activityTitanOtaBinding.customDial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(TitanOtaActivity.this, TitanCustomDialActivity.class));

            }
        });
        activityTitanOtaBinding.firmOta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(TitanOtaActivity.this);
                }
                if (waitingDialog.isShowing()) {
                    return;
                }
                waitingDialog.show();
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        EABleOta eaBleOta = getOtaFile();
                        if (mHandler != null) {
                            Message message = new Message();
                            message.what = 0x44;
                            message.obj = eaBleOta;
                            mHandler.sendMessage(message);
                        }


                    }
                }.start();

            }
        });
    }

    private String getAgpsFilePath() {
        if (TextUtils.isEmpty(agpsFilePath)) {
            try {
                InputStream qzssStream = getAssets().open("gps-lle_gps.lle");
                agpsFilePath = save2File(qzssStream, System.currentTimeMillis() + ".bin");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return agpsFilePath;
    }

    private String getDialFilePath() {
        if (TextUtils.isEmpty(dialFilePath)) {
            try {
                InputStream dialStream = getAssets().open("a11_online_watchface_06_02_ota.bin");
                String fName = System.currentTimeMillis() + ".bin";
                String tempDialFilePath = save2File(dialStream, fName);
                if (!TextUtils.isEmpty(tempDialFilePath) && new File(tempDialFilePath).exists()) {
                    oriFileSize = (int) new File(tempDialFilePath).length();
                    //先处理文件流
                    String iFilePath = EABleManager.getInstance().handleTitanOnlineDial(getExternalCacheDir().getAbsolutePath(), fName);
                    if (!TextUtils.isEmpty(iFilePath) && new File(iFilePath).exists()) {
                        File compressFile = new File(getExternalCacheDir(), "compress_" + fName);
                        if (!compressFile.exists()) {
                            compressFile.createNewFile();
                        }
                        //  Lz4Compressor.INSTANCE.compressFile(iFilePath, compressFile.getAbsolutePath());
                        int result = new PreLz4().editData(iFilePath, compressFile.getAbsolutePath());
                        if (result == 0) {
                            dialFilePath = compressFile.getAbsolutePath();
                        }
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dialFilePath;
    }

    private EABleOta getOtaFile() {
        try {
            InputStream otaFile = getAssets().open("titan_9.9.9_ota.bin");
            String fName = System.currentTimeMillis() + ".bin";
            String tempDialFilePath = save2File(otaFile, fName);
            if (!TextUtils.isEmpty(tempDialFilePath) && new File(tempDialFilePath).exists()) {
                //获取OTA文件信息
                TitanOtaFileInfo titanOtaFileInfo = EABleManager.getInstance().getTitanOtaFileInfo(getExternalCacheDir().getAbsolutePath(), fName);
                Log.e(TAG, "获取到的固件信息：" + JSON.toJSONString(titanOtaFileInfo));
                if (titanOtaFileInfo != null && titanOtaFileInfo.otaType != null) {
                    EABleOta eaBleOta = new EABleOta();
                    eaBleOta.setOtaType(EABleOta.OtaType.apollo);
                    eaBleOta.setFilePath(tempDialFilePath);
                    eaBleOta.setTitanId(titanOtaFileInfo.fId);
                    eaBleOta.setTitanAddr(titanOtaFileInfo.fAddr);
                    eaBleOta.setTitanCrc(titanOtaFileInfo.fCrc);
                    eaBleOta.setTitanByteSize(titanOtaFileInfo.fSize);
                    eaBleOta.setVersion(titanOtaFileInfo.fVersion);
                    return eaBleOta;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "OTA文件处理时出现错误");
        }
        return null;
    }

    private String save2File(InputStream inputStream, String fName) {

        try {
            File file = new File(getExternalCacheDir(), fName);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream os = new FileOutputStream(file);
            int read = 0;
            byte[] bytes = new byte[1024 * 1024];
            //先读后写
            while ((read = inputStream.read(bytes)) > 0) {
                byte[] wBytes = new byte[read];
                System.arraycopy(bytes, 0, wBytes, 0, read);
                os.write(wBytes);
            }
            os.flush();
            os.close();
            inputStream.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getFirmOtaFilePath() {
        return null;
    }

    @Override
    protected void onDestroy() {

        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }

        super.onDestroy();
    }

}
